package utils

import (
	"Trace/constant"
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"

	"github.com/thedevsaddam/gojsonq"
)

func DoRequest(contractName string, contractAddress string, funcName string, abi string, userAdress string, funcParam []interface{}) []byte {
	requestBody := map[string]interface{}{
		"user":            userAdress,
		"contractName":    contractName,
		"contractAddress": contractAddress,
		"funcName":        funcName,
		"contractAbi":     json.RawMessage(abi),
		"funcParam":       funcParam,
		"groupId":         1,
		"useCns":          false,
		"useAes":          false,
		"cnsName":         contractName,
		"version":         "",
	}

	requestBodyJson, _ := json.Marshal(requestBody)
	//fmt.Println(string(requestBodyJson))
	req, err := http.NewRequest(http.MethodPost, constant.ReqUrl, bytes.NewBuffer(requestBodyJson))
	if err != nil {
		log.Fatal("DoRequest", err)
	}

	req.Header.Set("Content-Type", "application/json")

	client := http.Client{}
	resp, err := client.Do(req)

	if err != nil {
		log.Fatal("DoRequest", err)
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal("DoRequest", err)
	}
	defer resp.Body.Close()
	fmt.Println(string(body))
	return body
}

// 快速获取json中key的值
func GetJsonVal(body string, key string) interface{} {
	data := gojsonq.New().JSONString(body)
	res := data.Find(key)
	if res == nil {
		return ""
	}
	return res
}

// 去除json中的转义字符
func DisableEscapeHtml(data interface{}) (string, error) {
	bf := bytes.NewBuffer([]byte{})
	jsonEncoder := json.NewEncoder(bf)
	jsonEncoder.SetEscapeHTML(false)
	if err := jsonEncoder.Encode(data); err != nil {
		return "", err
	}
	return bf.String(), nil
}
